package com.yuuzy.qqclient.service;

import com.yuuzy.qqcommon.Message;
import com.yuuzy.qqcommon.MessageType;
import com.yuuzy.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 该类完成用户登录/注册等功能
 */
public class UserClientService {
	private Socket socket;
	private User u = new User();//我们可能在其他地方要使用user信息，因此做成成员属性

	//根据userId 和 pwd 到服务器验证该用户是否合法
	public boolean checkUser(String userID, String pwd) throws IOException, ClassNotFoundException {
		boolean b = false;
		//创建user对象
		u.setUserID(userID);
		u.setPassword(pwd);
		//连接服务器端发送u对象
		socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
		ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
		oos.writeObject(u);//发送User对象

		//读取从服务器端回复的message对象
		ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
		Object o = ois.readObject();
		Message ms = (Message) o;
		if (ms.getMesType().equals(MessageType.MESSAGE_LOGIN_SUCCEED)) {
			//登录OK
			//创建一个和服务器端保持通讯的线程->创建一个线程类ClientConnectServerThread
			ClientConnectServerThread clientConnectServerThread = new ClientConnectServerThread(socket);
			clientConnectServerThread.start();
			//为了客户端的拓展，将线程放到集合中管理
			ManageClientConnectServerThread.addClientConnectserverThread(userID, clientConnectServerThread);
			b = true;
		} else {
			//如果登录失败，我们就不能启动和服务器通信的线程，关闭socket
			socket.close();
		}
		return b;
	}

	//向服务器端请求在线用户列表
	public void onlineFriendList() throws IOException {
		//发送一↑Message、类型MESSAGE_GET_ONLINE_FRIEND
		Message message = new Message();
		message.setMesType(MessageType.MESSAGE_GET_ONLINE_FRIEND);
		message.setSender(u.getUserID());
		message.setGetter(u.getUserID());
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(
				ManageClientConnectServerThread.
						getClientConnectserverThread(u.getUserID()).
						getSocket().getOutputStream());
		objectOutputStream.writeObject(message);
	}
	//编写方法，退出客户端，并给服务端发送一个退出系统的message对象
	public void logout() throws IOException {
		Message message = new Message();
		message.setSender(u.getUserID());
		message.setGetter(u.getUserID());
		message.setMesType(MessageType.MESSAGE_CLIENT_EXIT);
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(
				ManageClientConnectServerThread.
						getClientConnectserverThread(u.getUserID()).
						getSocket().getOutputStream());
		objectOutputStream.writeObject(message);
		System.out.println(u.getUserID() + "退出系统");
		System.exit(0);//结束进程
	}

}
